<?php
namespace app\massage\model;

use app\admin\model\ShopOrderRefund;
use app\BaseModel;
use think\facade\Db;

class RefundOrder extends BaseModel
{
    //定义表名
    protected $name = 'massage_service_refund_order';



     protected $append = [

         'order_goods',

         'all_goods_num',

         'hx_user_text'

     ];


    /**
     * @author chenniang
     * @DataTime: 2021-09-23 16:52
     * @功能说明:
     */
     public function getHxUserText($value,$data){

         if(!empty($data['hx_user'])){

             $user_model = new User();

             $nickName = $user_model->where(['id'=>$data['user_id']])->value('nickName');

             return $nickName;
         }


     }



    /**
     * @author chenniang
     * @DataTime: 2021-03-26 16:48
     * @功能说明:
     */
    public function getImgsAttr($value,$data){

        if(!empty($value)){

            return explode(',',$value);
        }

    }

    /**
     * @param $value
     * @param $data
     * @功能说明:总商品数量
     * @author chenniang
     * @DataTime: 2021-03-25 14:39
     */
    public function getAllGoodsNumAttr($value,$data){

        if(!empty($data['id'])){

            $order_goods_model = new RefundOrderGoods();

            $dis = [

                'refund_id' => $data['id']
            ];

            $num = $order_goods_model->where($dis)->sum('num');

            return $num;
        }


    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-17 17:16
     * @功能说明:收货信息
     */
     public function getOrderGoodsAttr($value,$data){

         if(!empty($data['id'])){

             $goods_model = new RefundOrderGoods();

             $info = $goods_model->dataSelect(['refund_id'=>$data['id']]);

             return $info;

         }

     }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataList($dis,$page=10,$mapor=[]){

        $data = $this->alias('a')
                ->join('massage_service_refund_order_goods c','a.id = c.refund_id')
                ->join('shequshop_car_order d','a.order_id = d.id')
                ->where($dis)
                ->where(function ($query) use ($mapor){
                    $query->whereOr($mapor);
                })
                ->field('a.*,d.order_code as pay_order_code,d.pay_price')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();


        if(!empty($data['data'])){

            $user_model = new User();

            foreach ($data['data'] as &$v){

                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');

            }
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:46
     * @功能说明:小程序退款列表
     */
    public function indexDataList($dis,$where=[],$page=10){

        $data = $this->alias('a')
            ->join('massage_service_refund_order_goods c','a.id = c.refund_id','left')
            ->join('shequshop_car_order d','a.order_id = d.id','left')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->field('a.*,d.order_code as pay_order_code')
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-08 17:08
     * @功能说明:退款中
     */
    public function refundIng($cap_id){

        $dis = [

            'cap_id' => $cap_id,

            'status' => 1
        ];

        $count = $this->where($dis)->count();

        return $count;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['status'] = 1;

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 09:37
     * @功能说明:通过退款
     */
    public function passOrder($id,$price,$payConfig,$refund_user=0,$text=''){

        $refund_order= $this->dataInfo(['id'=>$id]);

        $order_model = new Order();

        $pay_order   = $order_model->dataInfo(['id'=>$refund_order['order_id']]);

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'订单状态错误'];
        }

        $update = [

            'status'      => 2,

            'refund_time' => time(),

            'refund_price'=> $price,

            'refund_text' => $text
        ];

//        $comm_model = new Commission();

        Db::startTrans();
        //分销佣金
//        $comm_model->refundComm($id);


        $res = $this->dataUpdate(['id'=>$refund_order['id']],$update);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试'];

        }
        //修改退款子订单的退款状态
        $order_refund_goods = new RefundOrderGoods();

        $res = $order_refund_goods->dataUpdate(['refund_id'=>$id],['status'=>2]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试1'.$res];

        }



        $order_update = [];

//        if($refund_order['apply_price']>0){

//            //服务费占总退款的比例
//            $ser_bin = $refund_order['service_price']/$refund_order['apply_price'];
//            //扣除退款后的服务费
//            $coach_price    = $pay_order['true_service_price'] - $price*$ser_bin;
//
//            $coach_price    = $coach_price>0?round($coach_price,2):0;
//
//            $order_update = [
//
//
//                'true_service_price'=> $coach_price,
//
//
//            ];
//        }

        //查看货是否退完了
        $refund_success = $this->checkRefundNum($refund_order['order_id']);
        //退完了 就修改订单状态
        if($refund_success==1){

            $order_update['pay_type'] = -1;

            if(!empty($pay_order['pay_type'])&&$pay_order['pay_type']<=3){
                //退换优惠券
                $coupon_model = new CouponRecord();

                $coupon_model->couponRefund($pay_order['id']);
            }

        }

        if(!empty($order_update)){

            $res = $order_model->dataUpdate(['id'=>$refund_order['order_id']],$order_update);

            if($res!=1){

                Db::rollback();

                return ['code'=>500,'msg'=>'退款失败，请重试2'];

            }

        }

        //退款
        if($price>0){

            $res = $this->refundCash($payConfig,$pay_order,$price,$id);

            if(!empty($res['code'])){

                Db::rollback();

                return ['code'=>500,'msg'=>$res['msg']];
            }

            if($res!=true){


                Db::rollback();

                return ['code'=>500,'msg'=>'退款失败，请重试2'];
            }

        }

        Db::commit();

        return true;

    }


    /**
     * @param $payConfig
     * @param $pay_order
     * @param $price
     * @param int $refund_id
     * @功能说明:退钱
     * @author chenniang
     * @DataTime: 2021-07-12 20:31
     */
    public function refundCash($payConfig,$pay_order,$price,$refund_id=0){

        $order_model = new Order();

        if(empty($pay_order['balance'])){
            //微信退款
            $response = orderRefundApi($payConfig,$pay_order['pay_price'],$price,$pay_order['transaction_id']);
            //如果退款成功修改一下状态
            if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

                $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$pay_order['order_code'];

                if(!empty($refund_id)){

                    $this->dataUpdate(['id'=>$refund_id],['out_refund_no'=>$response['out_refund_no']]);

                }else{

                    $order_model->dataUpdate(['id'=>$pay_order['id']],['coach_refund_code'=>$response['out_refund_no']]);
                }


            }else {
                //失败就报错
                $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

                return ['code'=>500,'msg'=> $discption];

            }

        }else{

            $user_model = new User();

            $water_model = new BalanceWater();

            $user = $user_model->dataInfo(['id'=>$pay_order['user_id']]);
            //修改用户余额
            $res = $user_model->dataUpdate(['id'=>$pay_order['user_id']],['balance'=>$price+$user['balance']]);

            if($res==0){

                return false;

            }
            //添加余额流水
            $insert = [

                'uniacid' => $pay_order['uniacid'],

                'user_id' => $pay_order['user_id'],

                'order_id'=> $pay_order['id'],

                'price'   => $price,

                'add'     => 1,

                'type'    => 2,

                'before_balance' => $user['balance'],

                'after_balance'  => $price+$user['balance'],
            ];

            $res = $water_model->dataAdd($insert);

            if($res==0){

                return false;

            }

        }

        return true;


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 10:29
     * @功能说明:检查改订单款退完了没
     */
    public function checkRefundNum($order_id){

        $order_goods_model = new OrderGoods();

        $order_refund_goods_model = new RefundOrderGoods();

        $order_model = new Order();

        $dis = [

            'order_id' => $order_id
        ];

        $goods_num = $order_goods_model->where($dis)->sum('num');

        $dis['status'] = 2;

        $refund_num= $order_refund_goods_model->where($dis)->sum('num');

        return $refund_num>=$goods_num?1:0;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 15:38
     * @功能说明:该天的退款
     */
    public function datePrice($date,$uniacid,$cap_id=0,$end_time='',$type=1){

        $end_time = !empty($end_time)?$end_time:$date+86399;

        $dis = [];

        $dis[] = ['status','=',2];

        $dis[] = ['create_time','between',"$date,$end_time"];

        $dis[] = ['uniacid',"=",$uniacid];

        if(!empty($cap_id)){

            $dis[] = ['cap_id','=',$cap_id];
        }

        if($type==1){

            $price = $this->where($dis)->sum('refund_price');

            return round($price,2);

        }else{

            $count = $this->where($dis)->count();

            return $count;
        }


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 13:33
     * @功能说明:申请退款
     */
    public function applyRefund($order,$input){

        $order_goods_model = new OrderGoods();

        $refund_price = 0;

        Db::startTrans();

        $list = $input['list'];


        foreach ($list as $k=>$value){

            if(!empty($value['id'])){

                $order_goods = $order_goods_model->dataInfo(['id'=>$value['id']]);


                if(empty($order_goods)){

                    return ['code'=>500,'msg'=>'商品未找到'];
                }

                if($value['num']>$order_goods['can_refund_num']||$value['num']==0){

                    return ['code'=>500,'msg'=>'退款数量错误'];

                }
                //退款金额
                $refund_price += $order_goods['true_price']*$value['num'];

                $list[$k]['goods_id']    = $order_goods['goods_id'];

                $list[$k]['goods_name']  = $order_goods['goods_name'];

                $list[$k]['goods_cover'] = $order_goods['goods_cover'];

                $list[$k]['goods_price'] = $order_goods['goods_price'];

                $list[$k]['circle'] = $order_goods['circle'];

                $res = $order_goods_model->where(['id'=>$value['id']])->update(['can_refund_num'=>$order_goods['can_refund_num']-$value['num']]);

                if($res!=1){

                    Db::rollback();

                    return ['code'=>500,'msg'=>'申请失败'];

                }
            }
        }

        $car_price = 0;

        if($refund_price<=0){

//            Db::rollback();
//
//            return ['code'=>500,'msg'=>'退款金额至少为0.01元'];
        }

        $insert = [

            'uniacid'    => $order['uniacid'],

            'user_id'    => $order['user_id'],

            'total_circle' => $order['total_circle'],

            'order_code' => orderCode(),

            'apply_price'=> round($refund_price,2),

            'service_price'=> $refund_price,

            'order_id'   => $order['id'],

            'text'       => $input['text'],

            'car_price'  => $car_price,

            'imgs'       => !empty($input['imgs'])?implode(',',$input['imgs']):'',

            'balance'    => !empty($order['balance'])?$refund_price:0,


        ];

        $res = $this->dataAdd($insert);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'申请失败'];

        }

        $refund_id = $this->getLastInsID();

        $refund_goods_model = new RefundOrderGoods();

        foreach ($list as $value){

            $insert = [

                'uniacid'        => $order['uniacid'],

                'order_id'       => $order['id'],

                'refund_id'      => $refund_id,

                'order_goods_id' => $value['id'],

                'goods_id'       => $value['goods_id'],

                'goods_name'     => $value['goods_name'],

                'goods_cover'    => $value['goods_cover'],

                'num'            => $value['num'],

                'goods_price'    => $value['goods_price'],

                'circle'         => $value['circle'],

                'status'         => 1,
            ];

            $res = $refund_goods_model->dataAdd($insert);

            if($res!=1){

                Db::rollback();

                return ['code'=>500,'msg'=>'申请失败'];

            }

        }

        Db::commit();

        return $refund_id;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-12 09:23
     * @功能说明:获取订单已经退款的数量
     */
    public function refundNum($order_goods_id){

        $dis = [

            'b.order_goods_id' => $order_goods_id,

            'a.status'   => 2
        ];

        $num = $this->alias('a')
                ->join('massage_service_refund_order_goods b','a.id = b.refund_id')
                ->where($dis)
                ->group('b.order_goods_id')
                ->sum('b.num');

        return $num;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-12 12:04
     * @功能说明:拒绝退款
     */
    public function noPassRefund($refund_id){

        $dis = [

            'id' => $refund_id
        ];

        $refund_order = $this->dataInfo($dis);

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'退款状态错误'];

        }

        $update = [

            'status'      => 3,

            'refund_time' => time()

        ];

        Db::startTrans();

        $res = $this->dataUpdate($dis,$update);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试'];

        }
        //修改退款子订单的退款状态
        $order_refund_goods = new RefundOrderGoods();

        $res = $order_refund_goods->dataUpdate(['refund_id'=>$refund_id],['status'=>3]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试'];

        }

        Db::commit();

        return true;

    }










}